<template>
  <div>
    <resource ref="res" @setResource="setResource" @editSetResource="editSetResource"/>
    <play-video ref="video" :video-url="videoUrl"/>
    <el-form ref="form" :model="form.course" :inline="true" :rules="rules" label-width="120px" style="margin: 5px;">
      <div class="dd-portlet">
        <div class="dd-title">
          <span>课程信息</span>
        </div>
        <div class="dd-body">
          <el-row>
            <el-col :span="8">
              <el-form-item label="课程名称" class="dd-label" prop="courseName">
                <el-input v-model="form.course.courseName" style="width: 320px;" placeholder="课程名称"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item label="课程分类" class="dd-label" prop="typeId">
                <treeselect v-model="form.course.typeId" class="treeselect-main" :options="courseType" style="width: 320px" placeholder="选择课程分类"/>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="8">
              <el-form-item label="课程时长" class="dd-label" prop="classHour">
                <el-input v-model="form.course.classHourStr" style="width: 320px" placeholder="根据视频时长自动计算"
                          disabled></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="课程状态" class="dd-label" prop="status">
                <el-select v-model="form.course.status" style="width: 320px" placeholder="课程状态">
                  <el-option v-for="item in dicts" :key="item.value" :label="item.label" :value="item.value-0">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="课程标签" class="dd-label" prop="source">
                <el-input v-model="form.course.source" style="width: 320px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <!-- <el-col :span="8">
              <el-form-item label="课程讲师" class="dd-label" prop="teacherId">
                <el-select v-model="form.course.teacherId" style="width: 320px" filterable placeholder="请选择">
                  <el-option v-for="item in teacherList" :key="item.id" :label="item.label" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>

          <!-- <el-row>
            <el-col :span="8">
              <el-form-item label="推荐课程" class="dd-label" prop="isHot">
                <el-select v-model="form.course.isHot" style="width: 320px" placeholder="是否推荐课程">
                  <el-option v-for="item in isHotList" :key="item.value" :label="item.label" :value="item.value-0">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="热门课程" class="dd-label" prop="isRecommend">
                <el-select v-model="form.course.isRecommend" style="width: 320px" placeholder="是否热门课程">
                  <el-option v-for="item in isRecommendList" :key="item.value" :label="item.label" :value="item.value-0">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row> -->

          <el-row>
            <el-col :span="8">
              <el-form-item label="课程介绍" class="dd-label" prop="courseDesc">
                <el-input type="textarea" v-model="form.course.courseDesc" rows="9" :autosize="{ minRows: 7, maxRows: 12}" maxlength="200"
                          placeholder="请输入课程简介,200字以内" style="width: 320px;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="课程封面" class="dd-label">
                <el-upload
                  class="avatar-uploader"
                  accept=".jpg,.jpeg,.png"
                  :action="fileUploadUrl"
                  :show-file-list="false"
                  :on-success="themeHandleSuccess"
                  v-loading="themeLoading"
                  :before-upload="beforeThemeUpload">
                  <img v-if="themeUrl" :src="themeUrl" class="avatar"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="dd-title">
            <span>课程目录</span>
            <span class="marginleft">
              <el-popover placement="top-start" width="110" trigger="hover" content="新增课程目录">
                <el-button slot="reference" size="mini" type="success" icon="el-icon-plus" @click="addChapter()"
                           circle></el-button>
              </el-popover>
            </span>
          </div>
          <div>
            <el-card class="box-card" v-for="(item,index) in form.courseChapter" :key="index">
              <div slot="header" class="clearfix">
                <span>{{item.label}}</span>
                <el-button style="float: right; padding: 1px" type="text" @click="delChapter(index)">删除目录</el-button>
                <el-button style="float: right; padding: 1px" type="text" @click="editChapter(index)">编辑目录</el-button>
              </div>
              <el-row v-for="(resource,resourceIndex) in item.courseResourceList" :key="resourceIndex">
                <el-col :span="9">
                  <div>
                    <span><i class="el-icon-video-camera"></i></span>{{resource.resourceName}}
                  </div>
                </el-col>
                <!-- <el-col :span="3">
                  <div>{{resource.classHourStr}}</div>
                </el-col> -->
                <el-col :span="9">
                  <div><span>{{resource.resourceFileName}}</span></div>
                </el-col>
                <!-- <el-col :span="3">
                  <div><span>下载权限：</span>
                    <el-switch v-model="resource.isDownload" :active-value="1" :inactive-value="0"></el-switch>
                  </div>
                </el-col> -->
                <el-col :span="3">
                  <div class="buttonCss">
                    <el-popover placement="top-start" width="110" trigger="hover" content="编辑课程子目录">
                      <el-button slot="reference" size="mini" type="primary"
                                 @click="editResource(resource,index,resourceIndex)" icon="el-icon-edit" circle/>
                    </el-popover>
                    <el-popover placement="top-start" width="110" trigger="hover" content="删除课程子目录">
                      <el-button slot="reference" size="mini" type="danger" @click="delResource(index,resourceIndex)"
                                 icon="el-icon-delete" circle/>
                    </el-popover>
                    <!-- <el-popover placement="left-start" width="50" trigger="hover" content="播放\预览">
                      <el-button slot="reference" size="mini" type="success" @click="playVideo(resource)"
                                 icon="el-icon-video-play" circle/>
                    </el-popover> -->
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-bottom: -10px;">
                <el-col :span="12" :offset="11">
                  <div>
                    <el-popover placement="top-start" width="110" trigger="hover" content="新增课程子目录">
                      <el-button slot="reference" size="mini" type="success" @click="addResource(index)" icon="el-icon-plus" circle/>
                    </el-popover>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </div>
          <div class="footer">
            <el-button type="info" @click="goBack" round>取消</el-button>
            <el-button :loading="loading" type="primary" @click="doSubmit" round>确认</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { add, info } from '@/api/business/course'
  import { findUser } from '@/api/business/user'
  import playVideo from '../components/playVideo'
  import { typeTree } from '@/api/business/courseType'
  import { getPlanList } from '@/api/business/trainPlan'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import resource from './resource'
  import { getUrl, getName, formatSeconds } from '@/utils/index'
  import initDict from '@/mixins/initDict'

  export default {
    components: { resource, playVideo },
    mixins: [initDict],
    data() {
      return {
        fileUploadUrl: process.env.FILE_UPLOAD,
        themeLoading:false,
        queryId: this.$route.query.id,
        loading: false,
        videoUrl: '',
        teacher: 'r_teacher',
        courseType: [],
        chapter: [],
        teacherList: [],
        planList: [],
        themeImage: [],
        courseFile: [],
        themeUrl: null,
        // isHotList:[{value:0,label:"否"},{value:1,label:"是"}],
        // isRecommendList:[{value:0,label:"否"},{value:1,label:"是"}],
        resourceSort: 0,
        resource: {
          chapterId: '',
          resourceName: '',
          resourceFile: '',
          resourceFileName: '',
          classHour: 0,
          classHourStr: '',
          sort: 0,
          isDownload: 0
        },
        chapterSort: 0,
        chapterList: {
          id: '',
          label: '', //章节名称
          courseId: '',
          sort: 0,
          courseResourceList: []
        },
        form: {
          course: {
            id: null,
            courseName: '',
            themeImage: '',
            source: '',
            courseFile: '',
            classHour: 0,
            classHourStr: '',
            courseDesc: '',
            //teacherId: '',
            chapterId: '',
            typeId: null,
            planId: '',
            status: null
          },
          courseChapter: []
        },
        rules: {
          courseName: [
            { required: true, message: '请输入课程名称', trigger: 'blur' }
          ],
          // typeId: [
          //   { required: true, message: '请输选择课程分类', trigger: 'blur' }
          // ],
          themeImage: [
            { required: true, message: '请上传课程主题图片', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择课程状态', trigger: 'blur' }
          ],
          source: [
            { required: true, message: '请填写课程标签', trigger: 'blur' }
          ],
          courseDesc: [
            { required: true, message: '请填写课程简介', trigger: 'blur' }
          ],
          // isHot: [
          //   { required: true, message: '请选择是否热门课程', trigger: 'blur' }
          // ],
          // isRecommend: [
          //   { required: true, message: '请选择是推荐门课程', trigger: 'blur' }
          // ]
        }
      }
    },
    created() {
      this.$nextTick(() => {
        this.getDict('course_status')
        this.initData()
        if (this.queryId) {
          this.queryInfo()
        }
      })
    },
    methods: {
      getName,
      getUrl,
      formatSeconds,
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.doAdd()
          }
        })
      },
      doAdd() {
        if(this.themeUrl==null || this.themeUrl==""){
          this.$message({
            message: '请上传课程封面！！',
            type: 'warning'
          })
          return
        }
        if (this.form.courseChapter.length === 0) {
          this.$message({
            message: '请添加课程目录',
            type: 'warning'
          })
          return
        }
        let resourceAlert = false
        let resourceInfo = ''
        this.form.courseChapter.forEach(item => {
          if (item.courseResourceList.length === 0) {
            resourceAlert = true
            resourceInfo = item.label
          }
        })
        if (resourceAlert) {
          this.$message({
            message: '请添加【' + resourceInfo + '】目录课程资源',
            type: 'warning'
          })
          return
        }
        add(this.form).then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.goBack()
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      addChapter() {
        this.$prompt('请输入课程目录', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.chapterSort++
          const chapterList = {
            id: '',
            label: value,
            courseId: '',
            sort: this.chapterSort,
            courseResourceList: []
          }
          this.form.courseChapter.push(chapterList)
        })
      },
      delChapter(index) {
        this.form.courseChapter.splice(index, 1)
        //this.getTotalClassHour()
      },
      editChapter(index) {
        this.$prompt('请输入课程目录', '提示', {
          confirmButtonText: '确定',
          inputValue: this.form.courseChapter[index].label,
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.form.courseChapter[index].label = value
        })
      },
      addResource(index) {
        this.$refs.res.dialog = true
        this.$refs.res.index = index
      },
      setResource(data, index) {
        if (this.form.courseChapter[index].courseResourceList.length !== 0) {
          data.sort = this.form.courseChapter[index].courseResourceList.length - 1
        }
        this.form.courseChapter[index].courseResourceList.push(data)
        //this.getTotalClassHour()
      },
      editSetResource(data, index, resourceIndex) {
        this.form.courseChapter[index].courseResourceList.splice(resourceIndex, 1, data)
        //this.getTotalClassHour()
      },
      getTotalClassHour() {
        let totalHour = 0
        this.form.courseChapter.forEach(item => {
          item.courseResourceList.forEach(resource => {
            totalHour += resource.classHour
          })
        })
        this.form.course.classHour = totalHour
        this.form.course.classHourStr = formatSeconds(totalHour)
      },
      playVideo(resource) {
        if(resource.resourceFileName.indexOf("pdf")>0 || resource.resourceFileName.indexOf("PDF")>0){
          var imageUrl="";
          if(resource.resourceFile!=""){
            var array=eval('(' + resource.resourceFile + ')');
            if(Object.prototype.toString.call(array)==='[object Array]'){
              imageUrl=array[0].url.replaceAll("download=1","download=0");
            }
          }
          window.open(imageUrl)
        }else{
          this.videoUrl = getUrl(resource.resourceFile)
          this.$refs.video.dialog = true
        }
      },
      editResource(resource, index, resourceIndex) {
        this.$refs.res.index = index
        this.$refs.res.resourceIndex = resourceIndex
        this.$refs.res.resource = JSON.parse(JSON.stringify(resource))
        this.$refs.res.resourceFile = JSON.parse(resource.resourceFile)
        //this.$refs.res.resource.classHourStr = formatSeconds(resource.classHour)
        this.$refs.res.dialog = true
        this.$refs.res.edit = true
      },
      delResource(index, resourceIndex) {
        this.form.courseChapter[index].courseResourceList.splice(resourceIndex, 1)
        //this.getTotalClassHour()
      },
      beforeThemeUpload(file) {
        var imgfileType="'image/jpeg','image/jpg','image/pjpeg','image/x-png','image/png'";
        const isJPG =imgfileType.indexOf(file.type )>0;
        if (!isJPG) {
          this.$message.error('上传课程封面图片只能是 jpg、png、jpeg 格式!')
          return false;
        }
        this.themeLoading=true
      },
      themeHandleSuccess(response, file, fileList) {
        this.form.course.themeImage = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.themeUrl = uploadFile.url
        this.form.course.themeImage.push(uploadFile)
        this.form.course.themeImage = JSON.stringify(this.form.course.themeImage)
        this.$refs.form.validateField('themeImage')
        this.themeLoading=false
      },
      queryInfo() {
        info(this.queryId).then(data => {
          this.form = data
          this.themeUrl = getUrl(data.course.themeImage)
          data.courseChapter.forEach(item => {
            item.courseResourceList.forEach(resource => {
              resource.resourceFileName = getName(resource.resourceFile)
              //resource.classHourStr = formatSeconds(resource.classHour)
            })
          })
          //this.form.course.classHourStr = formatSeconds(this.form.course.classHour)
          this.chapterSort = data.courseChapter.length;
        })
      },
      initData() {
       // this.getCourseType()
        //this.getTeacher()
       // this.getPlan()
      },
      getCourseType() {
        typeTree().then(data => {
          this.courseType = data
        })
      },
      getPlan() {
        getPlanList().then(data => {
          this.planList = data
        })
      },
      getTeacher() {
        findUser(this.teacher).then(data => {
          this.teacherList = data
        })
      },
      goBack() {
        this.$router.go(-1)
      }
    }
  }
</script>

<style>
  .marginleft {
    margin-left: 20px;
  }

  .marginleft el-collapse-item {
    margin-left: 20px;
  }

  .el-collapse-item__header {
    font-weight: 800;
    font-size: 14px;
  }

  .el-row {
    margin-bottom: 10px;
  }

  .box-card {
    margin-bottom: 10px;
  }

  .box-card .clearfix span {
    font-weight: 800;
  }

  .buttonCss {
    text-align: center;
  }
</style>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .footer {
    height: 100px;
    width: 100%;
    text-align: center;
    bottom: 0;
    padding-top: 20px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .treeselect-main {
    margin-top: 1px;
    line-height: 35px;
    .vue-treeselect__placeholder {
      line-height: 35px;
    }
    .vue-treeselect__control {
      height: 36px;
    }
  }
</style>
